package com.example.cofeed.activity.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SPUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.cofeed.MainActivity;
import com.example.cofeed.R;
import com.example.cofeed.activity.ArticeCollectActivity;
import com.example.cofeed.activity.EditUserInfoActivity;
import com.example.cofeed.activity.HistoryActivity;
import com.example.cofeed.activity.LoginActivity;
import com.example.cofeed.activity.MessageNotificationActivity;
import com.example.cofeed.activity.MyAttentionActivity;
import com.example.cofeed.activity.MyDemandActivity;
import com.example.cofeed.activity.MyMsgActivity;
import com.example.cofeed.activity.SettingActivity;
import com.example.cofeed.activity.ShareActivity;
import com.example.cofeed.activity.WebViewActivity;
import com.example.cofeed.adapter.MineAdapter;
import com.example.cofeed.api.APIUrl;
import com.example.cofeed.base.BaseFragment;
import com.example.cofeed.constant.IntentKeyConstant;
import com.example.cofeed.constant.SputilsConstant;
import com.example.cofeed.even.LoginEeven;
import com.example.http.HttpManager;
import com.example.http.MainHojmeBean;
import com.example.http.MineTab;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MyFragment extends BaseFragment {
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.iv_avatar)
    CircleImageView mIvAvatar;
    @BindView(R.id.tv_name)
    TextView mTvName;
    @BindView(R.id.tv_attention)
    TextView mTvAttention;
    @BindView(R.id.tv_lljl)
    TextView mTvLljl;
    @BindView(R.id.tv_wdxx)
    TextView mTvWdxx;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;

    @Override
    protected boolean isBindEventBus() {
        return true;
    }

    @Override
    protected View initViews(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my, container, false);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initRecyclerView();
//        getData();
    }

    @Override
    protected void initData() {
        mRefreshLayout.setEnableLoadMore(false);
        mRefreshLayout.setOnRefreshListener(refreshLayout -> {
            getData();
            finishRefresh(mRefreshLayout);

        });
    }

    MineAdapter mineAdapter;

    private void initRecyclerView() {

        mineAdapter = new MineAdapter();
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(mineAdapter);


        mineAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                itemClick(mineAdapter.getData().get(position));
            }
        });
    }


    private void itemClick(MineTab mineTab) {

        switch (mineTab.getTitle()) {

            case "我的供求":
                ActivityUtils.startActivity(MyDemandActivity.class);
                break;
            case "消息中心":
//                ActivityUtils.startActivity(SystemMessagesActivity.class);
                ActivityUtils.startActivity(MessageNotificationActivity.class);
                break;
            case "我的关注":
                ActivityUtils.startActivity(MyAttentionActivity.class);
                break;
            case "浏览记录":
                ActivityUtils.startActivity(HistoryActivity.class);
                break;
            case "设置":
                ActivityUtils.startActivity(SettingActivity.class);
                break;
            case "我的短信":
//                ActivityUtils.startActivity(MessageNotificationActivity.class);
                ActivityUtils.startActivity(MyMsgActivity.class);
                break;
            case "邀请好友":
                Intent shareIntent = new Intent(getActivity(), ShareActivity.class);
                shareIntent.putExtra(IntentKeyConstant.URL, "https://m.cofeed.com/cofapp/app/index.html");
                shareIntent.putExtra(IntentKeyConstant.NAME, "天下粮仓网是一家大型专业化粮油饲料网站，以精准的市场调研数据和深度行业走势研究深受广大客户认可，通过天下粮仓网智能手机客户端可随时随地了解粮油及饲料原料最新价格快讯及走势分析。万千资讯，尽在“掌”握，助您抢占市场先机!");
                startActivity(shareIntent);
                break;
            case "我的收藏":
                ActivityUtils.startActivity(ArticeCollectActivity.class);
                break;
            case "商机收藏夹":
                Intent intent = new Intent(getActivity(), WebViewActivity.class);
                intent.putExtra(IntentKeyConstant.TYPE, 10);
                startActivity(intent);
                break;
            case "我的反馈":
                Intent intent1 = new Intent(getActivity(), WebViewActivity.class);
                intent1.putExtra(IntentKeyConstant.TYPE, 12);
                startActivity(intent1);
                break;

            default: {
                if (!TextUtils.isEmpty(mineTab.getUrl())) {
                    Intent intent3 = new Intent(getActivity(), WebViewActivity.class);
                    intent3.putExtra(IntentKeyConstant.URL, mineTab.getUrl());
                    startActivity(intent3);

                }

            }
        }
    }


    private void getData() {
        HttpManager.getHttpClient(APIUrl.MENU_USER, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {


                try {

                    String string = response.body().string();


                    JSONObject json = new JSONObject(string);

                    int code = json.getInt("code");

                    if (code != 200) {
                        return;
                    }

                    LogUtils.e("msg==== " + string);

                    MainHojmeBean mainHojmeBean = new Gson().fromJson(string, MainHojmeBean.class);
                    List<MineTab> data = mainHojmeBean.data;
                    Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mineAdapter.setNewData(data);

                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();

                }


            }
        });

    }


    @Override
    public void onResume() {
        super.onResume();


        if (!isHidden()) {
            List<MineTab> data = mineAdapter.getData();
            if (data == null || data.isEmpty()) {
                getData();
//                LogUtils.e("p---------------------------------------onreume getData");

            }
        }
//        LogUtils.e("p---------------------------------------onreume");
        if (ObjectUtils.isNotEmpty(SPUtils.getInstance().getString(SputilsConstant.TOKEN))) {
//            ApiService.userinfo_picname(this, new DialogCallback<LzyResponse<Map<String, String>>>() {
//                @Override
//                public void onSuccess(Response<LzyResponse<Map<String, String>>> response) {
//
//                }
//            });

            String picture = SPUtils.getInstance().getString(SputilsConstant.PICTURE);
            String name = SPUtils.getInstance().getString(SputilsConstant.NAME);

            if (ObjectUtils.isNotEmpty(picture)) {
                Glide.with(getActivity()).load(picture).into(mIvAvatar);
            }
            if (ObjectUtils.isNotEmpty(name)) {
                mTvName.setText(name);
            } else {
                mTvName.setText("未设置昵称");
            }
//            getView().findViewById(R.id.tv_edit).setVisibility(View.VISIBLE);

        } else {
            mTvName.setText("未登录");
//            getView().findViewById(R.id.tv_edit).setVisibility(View.INVISIBLE);
            Glide.with(getActivity()).load(R.mipmap.userimg).into(mIvAvatar);

        }

    }

    @OnClick({R.id.tv_edit, R.id.rl_wdgq, R.id.rl_wdxx, R.id.rl_wdgz, R.id.rl_lljl, R.id.rl_sz, R.id.rl_wddx,
            R.id.rl_yqhy, R.id.rl_wzsc, R.id.rl_sjscj, R.id.rl_wdfk})
    public void onViewClicked(View view) {


        if (ObjectUtils.isEmpty(SPUtils.getInstance().getString(SputilsConstant.TOKEN))) {
            ActivityUtils.startActivity(LoginActivity.class);
            return;
        }
        switch (view.getId()) {
            case R.id.tv_edit:
                ActivityUtils.startActivity(EditUserInfoActivity.class);
//                ActivityUtils.startActivity(AttentionMoreActivity.class);
                break;
            case R.id.rl_wdgq:
                ActivityUtils.startActivity(MyDemandActivity.class);
                break;
            case R.id.rl_wdxx:
//                ActivityUtils.startActivity(SystemMessagesActivity.class);
                ActivityUtils.startActivity(MessageNotificationActivity.class);
                break;
            case R.id.rl_wdgz:
                ActivityUtils.startActivity(MyAttentionActivity.class);
                break;
            case R.id.rl_lljl:
                ActivityUtils.startActivity(HistoryActivity.class);
                break;
            case R.id.rl_sz:
                ActivityUtils.startActivity(SettingActivity.class);
                break;
            case R.id.rl_wddx:
//                ActivityUtils.startActivity(MessageNotificationActivity.class);
                ActivityUtils.startActivity(MyMsgActivity.class);
                break;
            case R.id.rl_yqhy:
                Intent shareIntent = new Intent(getActivity(), ShareActivity.class);
                shareIntent.putExtra(IntentKeyConstant.URL, "https://m.cofeed.com/cofapp/app/index.html");
                shareIntent.putExtra(IntentKeyConstant.NAME, "天下粮仓网是一家大型专业化粮油饲料网站，以精准的市场调研数据和深度行业走势研究深受广大客户认可，通过天下粮仓网智能手机客户端可随时随地了解粮油及饲料原料最新价格快讯及走势分析。万千资讯，尽在“掌”握，助您抢占市场先机!");
                startActivity(shareIntent);
                break;
            case R.id.rl_wzsc:
                ActivityUtils.startActivity(ArticeCollectActivity.class);
                break;
            case R.id.rl_sjscj:
                Intent intent = new Intent(getActivity(), WebViewActivity.class);
                intent.putExtra(IntentKeyConstant.TYPE, 10);
                startActivity(intent);
                break;
            case R.id.rl_wdfk:
                Intent intent1 = new Intent(getActivity(), WebViewActivity.class);
                intent1.putExtra(IntentKeyConstant.TYPE, 12);
                startActivity(intent1);
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void noLogin(LoginEeven loginEeven) {
        ((MainActivity) getActivity()).mNavigationController.setSelect(0);
    }
}
